package com.ust.diamond;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.ObjectInputStream.GetField;

import javax.imageio.ImageIO;

import libsvm.svm;
import libsvm.svm_model;

public class SolveIt {
	
//	public static boolean debugMode = true;
	public static boolean debugMode = false;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			BufferedImage img;
			
			svm_model diamondModel = svm.svm_load_model("model.m");
			
			Toolkit tool = Toolkit.getDefaultToolkit();
			Dimension d = tool.getScreenSize();
			Rectangle rect = new Rectangle(d);
			Robot robot = new Robot();
			// Wait for 5 seconds.
			Thread.sleep(Data.SLEEP_TIME_BEFORE_GAME);
//			File f = new File("screenshot.jpg");
//			img = robot.createScreenCapture(rect);
//			ImageIO.write(img,"jpeg",f);
			
			
//			Chess chess = new Chess(img);
			while(true) {
				long startTime = System.currentTimeMillis();
				while(System.currentTimeMillis() - startTime < 62000) {		
					if(Data.NEED_SCOLL_UP) {
						mouseScrollUp(robot);
					}
					Diamond.clearColors();
					if(debugMode) {
						img = ImageIO.read(new File(Data.DEBUG_DATA_PATH));
//						int rgb = img.getRGB(686, 750);
//						System.out.print(rgb);
					} else {
						img = robot.createScreenCapture(rect);
					}
					Chess chess = new Chess(img, diamondModel);
	//				chess.print();
					Point point[] = chess.lookForClick();
					for(int i = 0; i < 2; i++) {
						Point pointClick = Data.GetPosForClick(point[i]);
						if(!debugMode) {
							mouseClick(robot, pointClick);
						}
					}
					if(debugMode) break;
				}
				Thread.sleep(Data.SLEEP_TIME_EACH_GAME);
				
				if(!Data.INFINITE_LOOP) break;
				
				img = robot.createScreenCapture(rect);
				int rgb = img.getRGB(Data.CANCEL_BUTTON.x, Data.CANCEL_BUTTON.y);
				if(rgb == Data.CANCEL_BUTTON_COLOR) {
					//press cancel
					mouseClick(robot, Data.CANCEL_BUTTON);					
					Thread.sleep(Data.SLEEP_TIME_AFTER_CANCEL_PRESSED);
				}
				//start a new game
				mouseClick(robot, Data.NEW_GAME_BUTTON);
			}
				
			
//			for(int i = 0; i < 8; i++) {
//				for(int j = 0; j < 8; j++) {
//					System.out.print(diamond[i][j].color + " ");
//				}
//				System.out.println();
//			}
			
//			ArrayList<Integer> colors = Diamond.getColors();
//			colors.clear();
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void mouseScrollUp(Robot robot) {
		robot.mouseWheel(-100);
	}
	
	public static void mouseClick(Robot robot, Point point) {
		robot.mouseMove(point.x, point.y);
		robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
		robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
	}
}
